#!/usr/local/bin/ruby
# Copyright (C) 2003-2010 Wang Pengcheng <wpc0000@gmail.com>
# , released under the MIT license
# You may obtain a template of the MIT License at
# http://www.opensource.org/licenses/mit-license.php
$KCODE = 'utf8'

require 'socket'
require 'timeout'

# check the name is the directory
def dir?(name)
  (File.directory? name)
end

def is_port_open?(ip, port)
  # the local file path
  unless port
    return dir? ip
  end
  begin
    timeout(10) do
      TCPSocket.new(ip, port)
    end
  rescue Timeout::Error, Errno::ECONNREFUSED, Errno::ENETUNREACH, Errno::EHOSTUNREACH
    puts 'Network Error'
    return false
  end
  return true
end

# run hg *args
def hg(args)
  targs=['hg']
  args.each do |a|
    targs<<'"'+a.gsub('"','\"')+'"'
  end
  cmd = targs.join(' ')
  system cmd
end

# Get the port
def get_port(pro)
  case pro
  when 'ssh':
    22
  when 'https':
    443
  when 'local':
    nil
  else
    nil
  end
end

USER = ARGV[1]
PASSWD = ARGV[2]
SERVER=ARGV[3]
PATH=ARGV[4]
PRO=ARGV[5]
DEST=PRO+'://'+USER+':'+PASSWD+'@'+SERVER+PATH

# the local directory?
unless get_port(PRO)
  DEST = SERVER
end

